<template>
  <div class="flex items-center gap-10">
    {{ text }}
    <n-popselect v-bind="{ trigger: 'click', ...attrs }" :options="state.list">
      <img class="h-16 w-16 cursor-pointer" :src="attrs.value ? activeColor : normColor" />
    </n-popselect>
  </div>
</template>
<script setup lang="jsx">
import { useAppStore } from '@/store'
import lightFilterNormal from '@/assets/images/light-filter-normal.png'
import lightFilterActive from '@/assets/images/light-filter-active.png'
import deepFilterNormal from '@/assets/images/deep-filter-normal.png'
import deepFilterActive from '@/assets/images/deep-filter-active.png'
defineOptions({
  name: 'MyFilter',
})
const attrs = useAttrs()
const props = defineProps({
  options: {
    type: [Array, Function],
    default: () => [],
  },
  labelKey: {
    type: String,
    default: 'label',
  },
  valueKey: {
    type: String,
    default: 'value',
  },
  text: {
    type: String,
    default: '',
  },
  resolveFn: {
    type: Boolean,
    default: true,
  },
})
const appStore = useAppStore()
const activeColor = computed(() => (appStore.isDeep ? deepFilterActive : lightFilterActive))
const normColor = computed(() => (appStore.isDeep ? deepFilterNormal : lightFilterNormal))
const state = reactive({
  list: [],
})
const methods = reactive({
  async initOptions() {
    let ary = []
    if (Array.isArray(props.options)) {
      ary = props.options
    } else if (typeof props.options === 'function') {
      if (props.resolveFn) {
        const { data } = await props.options()
        ary = data
      } else {
        ary = await props.options()
      }
    }
    state.list = [
      {
        label: `全部`,
        value: '',
      },
      ...ary.map((item) => ({ label: item[props.labelKey], value: item[props.valueKey] })),
    ]
  },
})
onBeforeMount(() => {
  methods.initOptions()
})
watch(
  () => props.options,
  () => {
    methods.initOptions()
  },
  {
    deep: true,
  }
)
</script>
<style lang="scss" scoped></style>
